<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/7/7
 * Time: 16:00
 */

namespace app\admin\controller;


use app\admin\model\GiftUrl;
use app\admin\model\GoldRoomEggPrize;
use redis\Redis;
use app\admin\model\GoldEgg;
class Balloon extends Index
{
    public $redis;
    public function __construct()
    {
        $redis = new \Redis();
        $redis->connect('127.0.0.1',6379);
        $redis->auth('');
        $this->redis = $redis;
    }
    /**
     * 2019-05-15 开始宝箱指定
     */

    /**
     * 砸蛋指定数据(指定历史,正在指定,添加用户的库存列表)
     */
    public function loopHistory(){

        $goldEggModel = new GoldEgg();
        $gold_egg_list = $goldEggModel->getDataList();
        //判断当前宝箱状态
        $redis = $this->redis;
       // halt($redis);
        $check_stop = $redis->get('open_box_defend');  //维护状态  $check_stop ==2 在维护中

        $stop_type = 1;

        if($check_stop){
            $check_stop = json_decode($check_stop,true);
            $stop_type = $check_stop['status'];
        }

        $all_id = $goldEggModel->where('status = 1')->field('id,egg_name')->select();
        $num = [];
        foreach ($all_id as $k => $v){
            //已追加的轮数
            $num[$v['id']] = $redis->get('gold_room_store_loop_add_'.$v['id'])?$redis->get('gold_room_store_loop_add_'.$v['id']):1;
        }
        return view()->assign(['stop_type'=>$stop_type,'num'=>$num,'gold_egg'=>$all_id,'gold_egg_list'=>$gold_egg_list]);
    }

    /**
     * @return \think\response\Json
     * 历史指定和当前指定
     */
    public function loopHistoryData(){

        $redis = $this->redis;

        $gold_egg = input('get.gold_egg');

        //当前指定
        $loop_now = $redis->hGetAll('add_looty_list_'.$gold_egg);
        $loop = [];

        foreach ($loop_now as $k => $v){
            if(!is_array($v)){
                $v = json_decode($v,true);
            }

            if($v['status'] == 1){
                $loop[] = [
                    'gold_egg_id'=>$gold_egg,
                    'user_id' => $v['user_id'],
                    'user_nickname' => $v['user_nickname'],
                    'prize_name' => $v['buffer']['prize_name'],
                    'loop' => $v['loop'],     //指定抽多少次
                    'loop_now' => $v['loop_now'],    //目前第多少次
                    'status' => $v['status'],   //1-未抽中 2：已抽中 3：已取消
                    'create_time' => $v['create_time']?date("Y-m-d H:i:s",$v['create_time']):'',
                    'update_time' => $v['update_time']?date("Y-m-d H:i:s",$v['update_time']):'',
                    'operator' => $v['operator'],
                ];
            }
        }

        //指定历史
        $loop_history = $redis->hGetAll('add_looty_list_history_'.$gold_egg);

        foreach ($loop_history as $k => $v){
            if(!is_array($v)){
                $v = json_decode($v,true);
            }

            if($v['status'] == 2 || $v['status'] == 3){
                $loop[] = [
                    'gold_egg_id'=>$gold_egg,
                    'user_id' => $v['user_id'],
                    'user_nickname' => $v['user_nickname'],
                    'prize_name' => $v['buffer']['prize_name'],
                    'loop' => $v['loop'],
                    'loop_now' => $v['loop_now'],
                    'status' => $v['status'],
                    'create_time' => $v['create_time']?date("Y-m-d H:i:s",$v['create_time']):'',
                    'update_time' => $v['update_time']?date("Y-m-d H:i:s",$v['update_time']):'',
                    'operator' => $v['operator'],
                ];
            }
        }

        return json($loop);
    }

    /**
     * 停服与放开
     */
    public function loopToogle(){
        $redis = $this->redis;
        $open_box_type = input('get.open_box_type',1);

        $res2 = $redis->set("open_box_defend",json_encode(['status'=>$open_box_type,'time'=>time()]));

        $returnData = [
            'code' => 100,
            'msg' => '服务切换成功!!',
        ];
        return json($returnData);
    }

    /**
     * 指定用户数据入库
     */
    public function loopUserDataAdd(){
        $redis = $this->redis;
        $u_id = input('post.u_id');
        $total_num = input('post.total_num');  //抽奖次数
        $id = input('post.id');      //礼物id
        $gold_egg_id =input('post.gold_egg_id');  //适用宝箱
        $gift_type =input('post.gift_type');  //帅吴留 1：普通礼物 3：道具

        $user_id = \app\admin\model\User::where('u_id','=',$u_id)->field('id,nickname')->find();
        $nickname = filterEmoji($user_id['nickname']);

        $GoldRoomEggPrize = \app\admin\model\GoldRoomEggPrize::where('id','=',$id)->find();


        $broadcastMsg = '';
        $sendAttachRoomMsg = '';

        if($gift_type == 1){
            $gift = \app\admin\model\GiftUrl::where('id','=',$GoldRoomEggPrize['gift_id'])->find();

            if ($gift['gift_type'] == 2 || $gift['diamonds'] >= 500) {
                //如果是万能碎片或者奖品价格>=500 发全员广播
                $gift_type = 2; //若添加的礼物为碎片 则为2
                $broadcastMsg = $GoldRoomEggPrize['gift_notice'];
            }else if (isset($gift['gift_notice'])) {
                $sendAttachRoomMsg = $GoldRoomEggPrize['gift_notice'];
            }
        }elseif ($gift_type == 3){
            $gift = \app\admin\model\Prop::where('id','=',$GoldRoomEggPrize['gift_id'])->field('prop_name as gift_name,prop_pic as gift_url')->find();
            $broadcastMsg = $GoldRoomEggPrize['gift_notice'];
        }

        $loop_add = [
            'user_id'=>$user_id['id'],//用户id-
            'user_nickname'=>$nickname,//用户昵称-
            'buffer' =>  [
                'id'=>$id,//库存表id
                'gift_id'=>$GoldRoomEggPrize['gift_id'],//礼物id
                'gift_type'=>$gift_type,//礼物类型(1,普通礼物,2,万能碎片，3，道具)
                'prize_name'=>$gift['gift_name'],//奖品名称-
                'prize_pic'=>$gift['gift_url'],//奖品图片
                'number'=>1,//奖品数量
                'sendAttachRoomMsg'=>$sendAttachRoomMsg,//房间广播
                'broadcastMsg'=>$broadcastMsg,//全服广播
            ],
            'loop'=>$total_num,//指定次数-
            'loop_now' => 0, //当前轮次
            'status' => 1,//指定状态(1,未启用,2已使用,3已取消)-
            'create_time' => time() , //指定时间-
            'update_time' => '',//中奖时间-
            'operator' => session('admin_name') ,//操作人员-
        ];

        $res = $redis->hSet('add_looty_list_'.$gold_egg_id,$user_id['id'],json_encode($loop_add));

        if($res)  {
            $this->success('设置成功');
        }
        else{
            $this->error('设置失败');
        }
    }

    /**
     * 取消指定用户
     */
    public function loopUserDataDel(){
        $redis = $this->redis;


        $user_id = input('get.user_id');
        $gold_egg_id = input('get.gold_egg_id');
        $loop_now = $redis->hGet('add_looty_list_'.$gold_egg_id,$user_id);
        if(!$loop_now){
            return ['code'=>100,'msg'=>'取消成功'];
        }
        if(!is_array($loop_now)){
            $loop_now = json_decode($loop_now,true);
        }
        $loop_now['status'] = 3;
        $loop_now['update_time'] = time();
        $loop_now['operator'] = session('admin_name') ;

        $res = $redis->hSet('add_looty_list_history_'.$gold_egg_id,$user_id.time(),json_encode($loop_now));
        $res2 = $redis->hDel('add_looty_list_'.$gold_egg_id,$user_id);

        if($res && $res2){
            return ['code'=>100,'msg'=>'取消成功'];
        }
        else{
            return ['code'=>-100,'msg'=>'取消失败'];
        }



    }


    //控制轮数
    public function loopSetData(){

        $gold_id = input('get.gold_id');

        $redis = $this->redis;
        $custom_loop = json_decode($redis->get('custom_loop_add_'.$gold_id),true);
        $data = [];
        //  halt($custom_loop);
        if(!empty($custom_loop)){

            foreach($custom_loop as $k => $v){

                $prizeInfo = GoldRoomEggPrize::where('id','=',$k)->find();
                if($prizeInfo['gift_type'] == 3)
                    $gift_name = \app\admin\model\Prop::where('id','=',$prizeInfo['gift_id'])->value('prop_name');
                else
                    $gift_name = GiftUrl::where('id','=',$prizeInfo['gift_id'])->value('gift_name');
                $arr['gift_name'] = $gift_name;  //奖品名
                $arr['loop_num'] = $v;          //循环轮数
                $arr['prize_id'] = $k;          //
                $data[] = $arr;
            }
        }
//        $giftModel = new GoldRoomEggPrize();
//        $gift_list = $giftModel->getGoldGift($gold_id);
        return view()->assign(['data'=>$data,'gold_id'=>$gold_id]);
    }

    public function loopSetDataAdd(){
        $redis = $this->redis;
        $gift_id = input('post.gift_id');
        $loop_num = intval(input('post.loop_num'));
        $gold_id = input('post.gold_id');

        $custom_loop = json_decode($redis->get('custom_loop_add_'.$gold_id),true);

        if(empty($custom_loop)){
            $arr[$gift_id] = $loop_num;
            $re = $redis->set('custom_loop_add_'.$gold_id,json_encode($arr));
        }else{
            $custom_loop[$gift_id] = $loop_num;
            $re = $redis->set('custom_loop_add_'.$gold_id,json_encode($custom_loop));
        }
        // dump($custom_loop);

        if($re) return ['code'=>100,'msg'=>'设置成功'];
        else return ['code'=>-100,'msg'=>'设置失败'];
    }

    public function loopSetDataDel(){
        $prize_id = input('prize_id');
        $gold_id = input('gold_id');
        $redis = $this->redis;
        $custom_loop = json_decode($redis->get('custom_loop_add_'.$gold_id),true);

        if(!empty($custom_loop[$prize_id])){
            unset($custom_loop[$prize_id]);
            $re = $redis->set('custom_loop_add_'.$gold_id,json_encode($custom_loop));
            if($re) return ['code'=>100,'msg'=>'修改成功'];
            else return ['code'=>-100,'msg'=>'修改失败'];


        }else return ['code'=>-100,'msg'=>'数据异常'];
    }


    public function changeGift()
    {
        $gift_type = input('gift_type');
        $giftModel = new GoldRoomEggPrize();
        $gift_list = $giftModel->getGiftData($gift_type);
        return $gift_list;
    }


}